package com.example.Util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class WechatUtil {

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    @Value("${wechat.session-url}")
    private String sessionUrl;

    public Map<String, String> getOpenid(String code) {
        RestTemplate restTemplate = new RestTemplate();
        String url = String.format(sessionUrl, appid, secret, code);
        String response = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(response);

        Map<String, String> result = new HashMap<>();
        result.put("openid", jsonObject.getString("openid"));
        result.put("session_key", jsonObject.getString("session_key"));
        return result;
    }
}